package com.easyui.controller;

import com.easyui.pojo.Menu;
import com.easyui.pojo.User;
import com.easyui.service.MenuService;
import com.easyui.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class SystemController {

    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;

    @RequestMapping("gologin.html")
    public String goLogin() {
        return "/login";
    }

    @RequestMapping("user_menu.html")
    @ResponseBody
    public List<Menu> userMenu(HttpSession session) {
        //User user = (User) session.getAttribute("SESSION_USER");
        Subject subject = SecurityUtils.getSubject();
        //return menuService.getUserMenu(user.getId());
        return menuService.getUserMenu((Integer) subject.getPrincipal());
    }

    @RequestMapping("login.html")
    public ModelAndView login(String name, String password, HttpSession session) {
        //判断参数不为空，略
        try {
            userService.doLogin(name, password);
        } catch (Exception e) {
            return new ModelAndView("/login", "message", "用户名或密码错误");
        }
        //session.setAttribute("SESSION_USER", user);
        return new ModelAndView("/index");
    }

    @RequestMapping("logout.html")
    public String logout(HttpSession session) {
        //session.setAttribute("SESSION_USER", null);
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "/login";
    }

    @RequestMapping("auth_error.html")
    public String error(HttpSession session) {
        return "/error";
    }

}
